/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * Project  : WebQQCore
 * Package  : iqq.im.module
 * File     : CoreModule.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2012-7-31
 * License  : Apache License 2.0
 */
package iqq.mk.module;

import java.awt.image.BufferedImage;

import iqq.im.QQActionListener;
import iqq.im.QQException;
import iqq.im.bean.QQAccount;
import iqq.im.core.QQContext;
import iqq.im.core.QQModule;
import iqq.im.event.QQActionEvent;
import iqq.im.event.QQActionEventArgs;
import iqq.im.event.QQActionFuture;
import iqq.im.event.QQNotifyEvent;
import iqq.im.event.QQNotifyEventArgs;
import iqq.im.event.future.ProcActionFuture;
import iqq.im.module.AbstractModule;
import iqq.mk.module.LoginModule;

/**
 * 登录模块，处理登录和退出
 *
 * @author solosky
 */
public class ProcModule extends AbstractModule {
	
	private LoginModule loginMod;

	public void init(QQContext context) throws QQException{
		super.init(context);
		loginMod = getContext().getModule(QQModule.Type.LOGIN);
	}
    /**  qq and password Login method
     * @param listener
     * @return
     */
    public QQActionFuture login(QQActionListener listener) {
        ProcActionFuture future = new ProcActionFuture(listener, true);
        doGetLoginSig(future);        
        return future;
    }

    
    
    
    private void doGetLoginSig(final ProcActionFuture future) {
    	loginMod.getLoginSig(new QQActionListener() {
            @Override
            public void onActionEvent(QQActionEvent event) {
                if (event.getType() == QQActionEvent.Type.EVT_OK) {
                	doCheckVerify(future);
                } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                    future.notifyActionEvent(
                            QQActionEvent.Type.EVT_ERROR,
                            (QQException) event.getTarget());
                }
            }
        });
    }
    private void doCheckVerify(final ProcActionFuture future) {
        if (future.isCanceled()) {
            return;
        }
        final QQAccount account = getContext().getAccount();        
        loginMod.checkVerify(account.getUsername(), new QQActionListener() {
            public void onActionEvent(QQActionEvent event) {
                if (event.getType() == QQActionEvent.Type.EVT_OK) {
                    QQActionEventArgs.CheckVerifyArgs args =
                            (QQActionEventArgs.CheckVerifyArgs) (event.getTarget());
                    account.setUin(args.uin);                    
                    if (args.result == 0) {
                    	 doWebLogin(args.code, future);
                    } else {
                        //doGetUnionSig(future);//have no idear for the normal login
                    	//try to use "IP changed warning url"
                    	//http://xui.ptlogin2.qq.com/iperror.html?style=6&lang=2052&appid=1600000084&daid=4&s_url=http%3A%2F%2Fappimg2.qq.com%2Fcard%2Findex_v3.html&f_url=loginerroralert
                    	doGetVerify("为了保证您账号的安全，请输入验证码中字符继续登录。", future);
                    }
                } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                    future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
                }

            }
        });
    }
    
    private void doGetVerify(final String reason, final ProcActionFuture future) {
        if (future.isCanceled()) {
            return;
        }
        QQAccount account = getContext().getAccount();
        LoginModule login = (LoginModule) getContext().getModule(QQModule.Type.LOGIN);
        login.getCaptcha(account.getUin(), new QQActionListener() {
            public void onActionEvent(QQActionEvent event) {
                if (event.getType() == QQActionEvent.Type.EVT_OK) {
                    QQNotifyEventArgs.ImageVerify verify = new QQNotifyEventArgs.ImageVerify();
                    verify.type = QQNotifyEventArgs.ImageVerify.VerifyType.LOGIN;
                    verify.image = (BufferedImage) event.getTarget();
                    verify.reason = reason;
                    verify.future = future;
                    getContext().fireNotify(new QQNotifyEvent(QQNotifyEvent.Type.CAPACHA_VERIFY, verify));
                } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                    future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
                }
            }
        });
    }
    
    @SuppressWarnings("unused")
	private void doGetUnionSig(final ProcActionFuture future) {
        if (future.isCanceled()) {
            return;
        }   
        
        loginMod.getSigNew(new QQActionListener() {
            public void onActionEvent(QQActionEvent event) {
                if (event.getType() == QQActionEvent.Type.EVT_OK) {
                    doGetImgBySig(future);
                } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                    future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
                }
            }			
        });
    }

    private void doGetImgBySig(final ProcActionFuture future) {
    	loginMod.getCapUnionImage(new QQActionListener() {
        public void onActionEvent(QQActionEvent event) {
            if (event.getType() == QQActionEvent.Type.EVT_OK) {
                QQNotifyEventArgs.ImageVerify verify = new QQNotifyEventArgs.ImageVerify();
                verify.type = QQNotifyEventArgs.ImageVerify.VerifyType.LOGIN;
                verify.image = (BufferedImage) event.getTarget();
                verify.reason = "Please input verify code:";
                verify.future = future;
                getContext().fireNotify(new QQNotifyEvent(QQNotifyEvent.Type.CAPACHA_VERIFY, verify));
            } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
            }
        }
    });
		
	}
	
    /**
     * <p>loginWithVerify.</p>
     *
     * @param verifyCode a {@link java.lang.String} object.
     * @param future     a {@link iqq.im.event.future.ProcActionFuture} object.
     * @return a {@link iqq.im.event.QQActionFuture} object.
     */
    public QQActionFuture loginWithVerify(String verifyCode, final ProcActionFuture future) {

        QQAccount account = getContext().getAccount();
        loginMod.ipWebLogin(account.getUsername(), account.getPassword(),
                account.getUin(), verifyCode, new QQActionListener() {
                    public void onActionEvent(QQActionEvent event) {
                        if (event.getType() == QQActionEvent.Type.EVT_OK) {
                        	future.notifyActionEvent(QQActionEvent.Type.EVT_OK, null);
                        } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                            future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
                        }
                    }
                });
    
        return future;
    }
    
	private void doWebLogin(String verifyCode, final ProcActionFuture future) {
        QQAccount account = getContext().getAccount();
        loginMod.webLogin(account.getUsername(), account.getPassword(),
                account.getUin(), verifyCode, new QQActionListener() {
                    public void onActionEvent(QQActionEvent event) {
                        if (event.getType() == QQActionEvent.Type.EVT_OK) {
                        	future.notifyActionEvent(QQActionEvent.Type.EVT_OK, null);
                        } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                            future.notifyActionEvent(QQActionEvent.Type.EVT_ERROR,(QQException) event.getTarget());
                        }
                    }
                });
    }
	
    
}
